

#import "APChatInputView.h"
#import "APVoiceReocrderManager.h"
#import "NSString+Category.h"
#import "APPlaceHolderTextView.h"
#import "SVGA.h"
#import <AVFoundation/AVFoundation.h>

@interface ChatVoicePowerView ()
@property (nonatomic, strong) SVGAImageView *svgaImageView;
@property (nonatomic, strong) UIImageView *stopRecordImageView;
@property (nonatomic, strong) UIImageView *microImageView;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation ChatVoicePowerView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = LYRGBAColor(0, 0, 0, 0.3);
        _bgImageView = [[UIImageView alloc] init];
        _bgImageView.image = [UIImage imageNamed:@"record_white_bg"];
        [self addSubview:_bgImageView];
        [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.right.equalTo(self);
            make.height.equalTo(_bgImageView.mas_width).multipliedBy(138.0 / 375.0);
        }];

        _microImageView = [[UIImageView alloc] init];
        _microImageView.image = [UIImage imageNamed:@"microphone_h"];
        [self addSubview:_microImageView];
        [_microImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_bgImageView).offset(44);
            make.centerX.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(62, 62));
        }];
        
        _stopRecordImageView = [[UIImageView alloc] init];
        _stopRecordImageView.hidden = true;
        _stopRecordImageView.image = [UIImage imageNamed:@"sound_red"];
        [self addSubview:_stopRecordImageView];
        [_stopRecordImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_bgImageView.mas_top).offset(-135);
            make.centerX.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(131, 84));
        }];
        
        _svgaImageView = [[SVGAImageView alloc] init];
        _svgaImageView.imageName = @"voice_recording";
        _svgaImageView.autoPlay = true;
        [self addSubview:_svgaImageView];
        [_svgaImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_bgImageView.mas_top).offset(-135);
            make.centerX.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(131, 84));
        }];
        
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [LYFont fontWithSize:16 fontName:LYFontNamepfm];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_bgImageView.mas_top).offset(-8);
            make.left.right.equalTo(self);
        }];
        
    }
    return self;
}

- (void)reload:(BOOL)isRecording{
    self.stopRecordImageView.hidden = isRecording;
    self.svgaImageView.hidden = !isRecording;
    self.microImageView.image = isRecording ? [UIImage imageNamed:@"microphone_h"]:[UIImage imageNamed:@"microphone_n"];

}

- (void)setMessage:(NSString *)message{
    _message = message;
    self.titleLabel.text = message;
}


@end

@interface ChatVoiceButton ()
{
    BOOL _isCancel;
    NSTimeInterval _beginTime;
    NSTimeInterval _endTime;
}

@end


@implementation ChatVoiceButton

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _isCancel = NO;
        _beginTime = 0;
        _endTime = 0;
    }
    return self;
}

- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    debugLog(@"%s--%@",__FUNCTION__,event);
    _seconds = 0;
    _beginTime = event.timestamp;
    self.backgroundColor = LYRGBColor(87, 61, 255);
    if ([self.delegate respondsToSelector:@selector(chatVoiceButtonPressed:)]) {
        [self.delegate chatVoiceButtonPressed:self];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _endTime = event.timestamp;
    self.backgroundColor =  LYRGBColor(87, 61, 255);
    if (_isCancel) {
        if ([self.delegate respondsToSelector:@selector(chatVoiceButtonCancel:touchStatus:)]) {
            [self.delegate chatVoiceButtonCancel:self touchStatus:DchatVoicebuttonStatusCancel];
        }
    }else{
        double seconds = _endTime - _beginTime;
        _seconds = seconds;
        if (seconds > 1) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(chatVoiceButtonUp:)]) {
                [self.delegate chatVoiceButtonUp:self];
            }
        }else{
            if ([self.delegate respondsToSelector:@selector(chatVoiceButtonCancel:touchStatus:)]) {
                [self.delegate chatVoiceButtonCancel:self touchStatus:DchatVoicebuttonStatusTimeShort];
            }
        }
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    CGFloat y = touchPoint.y;
    LYLog(@"===y========%f",y);
    if (y <= -100) {
        _isCancel = true;
        if ([self.delegate respondsToSelector:@selector(chatVoiceButtonCancel:touchStatus:)]) {
            [self.delegate chatVoiceButtonCancel:self touchStatus:DchatVoicebuttonStatusUpMoveCancel];
        }
      
    }else{
        _isCancel = false;
        if ([self.delegate respondsToSelector:@selector(chatVoiceButtonCancel:touchStatus:)]) {
            [self.delegate chatVoiceButtonCancel:self touchStatus:DchatVoicebuttonStatusUpMove];
        }
    }
//    DMLOG(@"%s--%@",__FUNCTION__,NSStringFromCGPoint(touchPoint));

}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    LYLog(@"%s",__FUNCTION__);
    _isCancel = true;
    if ([self.delegate respondsToSelector:@selector(chatVoiceButtonCancel:touchStatus:)]) {
        [self.delegate chatVoiceButtonCancel:self touchStatus:DchatVoicebuttonStatusTimeBreak];
    }}
@end


@interface APChatInputView ()<ChatVoiceButtonDelegate>
{
    UIFont *_inputTextFont;
    NSInteger _inputViewMaxHeight;
    NSInteger _inputStatus;//  0键盘 1语音
}
@property (nonatomic, strong) UIView *dmInputView;
@property (nonatomic, strong) UIButton *recordButton;//切换语音和键盘
@property (nonatomic, strong) ChatVoicePowerView *powerView;
@property (nonatomic, strong) UIButton *sendButton;

@end

@implementation APChatInputView



- (UIView *)dmInputView{
    if (!_dmInputView) {
        _dmInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 210)];
        _dmInputView.backgroundColor = LYRGBColor(240, 240, 240);
    }
    return _dmInputView;
}




- (ChatVoicePowerView *)powerView{
    if (!_powerView) {
        _powerView = [[ChatVoicePowerView alloc] init];
        UIWindow *window = UIApplication.sharedApplication.keyWindow;
        [window addSubview:_powerView];
        [_powerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(window);
        }];
    }
    return _powerView;
}

- (APPlaceHolderTextView *)textView{
    if (!_textView) {
        _textView = [[APPlaceHolderTextView alloc] init];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.layer.cornerRadius = 8;
        _textView.layer.masksToBounds = YES;
        _textView.textView.font = _inputTextFont;
        _textView.backgroundColor = LYRGBColor(18, 23, 78);
        _textView.textColor = UIColor.whiteColor;
        _textView.isPlaceHolderCenter = true;
    }
    return _textView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = LYRGBColor(16, 22, 43);
        
        _inputTextFont = [UIFont systemFontOfSize:17];
        _inputViewMaxHeight = 80;
        _inputStatus = 0;
        
        _recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_recordButton setBackgroundImage:[UIImage imageNamed:@"voice_icon"] forState:UIControlStateNormal];
        [_recordButton addTarget:self action:@selector(chatRecordButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_recordButton];
        [_recordButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(20);
            make.centerY.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(34, 34));
        }];
        
        _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendButton setBackgroundImage:[UIImage imageNamed:@"send_icon"] forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(sendButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_sendButton];
        [_sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).offset(-20);
            make.centerY.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(32, 32));
        }];
        
        
        [self addSubview:self.textView];
        [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_recordButton.mas_right).offset(23);
            make.right.equalTo(_sendButton.mas_left).offset(-24);
            make.centerY.equalTo(self);
            make.height.mas_equalTo(36);
        }];



        _voiceButton = [ChatVoiceButton buttonWithType:UIButtonTypeCustom];
        _voiceButton.hidden = YES;
        [_voiceButton setTitle:@"Hold to talk" forState:UIControlStateNormal];
        _voiceButton.layer.cornerRadius = 8;
        _voiceButton.layer.masksToBounds = true;
        _voiceButton.backgroundColor = LYRGBColor(87, 61, 255);
        _voiceButton.delegate = self;
        [self addSubview:_voiceButton];
        [_voiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_recordButton.mas_right).offset(23);
            make.right.equalTo(_sendButton.mas_left).offset(-24);
            make.centerY.equalTo(self);
            make.height.mas_equalTo(36);
        }];

 

    }
    return self;
}

- (void)setShowMediaInput:(BOOL)showMediaInput{
    _showMediaInput = showMediaInput;
    if (showMediaInput) {
        self.textView.frame = CGRectMake(CGRectGetMaxX(self.recordButton.frame) + 10, 5, ScreenWidth - CGRectGetMaxX(self.recordButton.frame) - 50, 40);
    }else{
        self.textView.frame = CGRectMake(10, 5, ScreenWidth - 20, 40);
    }
}

//按下录音键
- (void)chatVoiceButtonPressed:(ChatVoiceButton *)voiceButton{

    LYLog(@"%s",__FUNCTION__);
    self.powerView.hidden = false;
//    [APVoiceReocrderManager shareVoiceReocrder].delegate = self;
    [[APVoiceReocrderManager shareVoiceReocrder] startRecord:^(_Bool res, NSString *msg) {}];
}

//松开录音键
- (void)chatVoiceButtonUp:(ChatVoiceButton *)voiceButton{
    LYLog(@"%s",__FUNCTION__);
    WS(ws);
    [[APVoiceReocrderManager shareVoiceReocrder] stopRecord];
    [[APVoiceReocrderManager shareVoiceReocrder] voiceRecorderDidFinishRecording:^(NSString *filePath, NSString *fileName) {
        NSString *voiceFilePath= [[APVoiceReocrderManager shareVoiceReocrder] getCurrentFilePath];
        if (ws.delegate && [ws.delegate respondsToSelector:@selector(chatInputView:sendMediaType:filePath:)]) {
            [ws.delegate chatInputView:ws sendMediaType:DchatMessageTypeVoice filePath:voiceFilePath];
        }
    }];
    self.powerView.hidden = true;
}

//取消录音
- (void)chatVoiceButtonCancel:(ChatVoiceButton *)voiceButton touchStatus:(chatVoicebuttonStatus)status{
    LYLog(@"%s",__FUNCTION__);
    switch (status) {
        case DchatVoicebuttonStatusTimeShort:{
            [self.superview ShowProgressOnlyLabel:@"The recording time cannot be less than 1s"];
             [[APVoiceReocrderManager shareVoiceReocrder] stopRecord];
             [[APVoiceReocrderManager shareVoiceReocrder] deleCurrentRecordFile];
            self.powerView.hidden = true;
             break;
        }
        case DchatVoicebuttonStatusTimeBreak:
        case DchatVoicebuttonStatusCancel:{
            [[APVoiceReocrderManager shareVoiceReocrder] stopRecord];
            [[APVoiceReocrderManager shareVoiceReocrder] deleCurrentRecordFile];
            self.powerView.hidden = true;
            break;
        }
        case DchatVoicebuttonStatusUpMove:
            self.powerView.message = @"Release Send";
            [self.powerView reload:true];
            break;
        case DchatVoicebuttonStatusUpMoveCancel:
            self.powerView.message = @"Release Cancel";
            [self.powerView reload:false];
            [[APVoiceReocrderManager shareVoiceReocrder] stopRecord];
            [[APVoiceReocrderManager shareVoiceReocrder] deleCurrentRecordFile];
            break;
        default:
            break;
    }
}



- (void)chatViewInputControlAction:(UIControl *)sender{
    if (_inputStatus != 0) {
        _inputStatus = 0;
        self.textView.hidden = NO;
        self.voiceButton.hidden = YES;
        self.textView.textView.inputView = nil;
        [self.textView endEditing:YES];
        [self.textView becomeFirstResponder];
    }
}

#pragma mark 切换语音
- (void)chatRecordButtonAction:(UIButton *)sender{
    if (_inputStatus != 1) {//语音
        AVAuthorizationStatus Status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (Status == AVAuthorizationStatusRestricted || Status == AVAuthorizationStatusDenied) {
            [self.superview ShowProgressOnlyLabel:@"You have not authorised this permission."];
            return;
        }
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self->_inputStatus = 1;
                    [self.textView resignFirstResponder];
                    self.textView.textView.inputView = nil;
                    self.textView.hidden = YES;
                    self.voiceButton.hidden = NO;
                });
            } else {
                [self.superview ShowProgressOnlyLabel:@"You have not authorised this permission."];
            }
        }];
    }else{
        _inputStatus = 0;
        self.textView.hidden = NO;
        self.voiceButton.hidden = YES;
        self.textView.textView.inputView = nil;
        [self.textView endEditing:YES];
        [self.textView becomeFirstResponder];
    }
}

#pragma mark 切换发送多媒体界面
- (void)sendButtonDidClick:(UIButton *)sender{
    [self.textView endEditing:YES];
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatInputView:sendMessage:)]) {
        [self.delegate chatInputView:self sendMessage:self.textView.textView.text];
    }
    self.textView.textView.text = @"";
}



@end
